// 导入数据库操作模块 '/dm'
const db = require('../db/index')

// 初始化, 根据部门找所有id 
exports.getIdByDep = (req,res) => { 
	const sql = 'select * from users where department = ?'
	db.query(sql, req.body.department, (err, result) => {
		if (err) return res.cc(err)
		// res.send(JSON.stringify(result[0].id))
		let idArr = [] 	
		result.forEach((e) => {
			idArr.push(e.id)
		})
		res.send({
			status: 0,
			ids: idArr
		})
	})
}

// 接收对象为全体成员 newId
exports.setAllDepartment = (req, res) => {
	const sql = "select id from message where message_receipt_object = '全体成员' and message_status = 0 "
	db.query(sql, (err, result) => {
		if (err) return res.cc(err) 
		const sql0 = 'select read_list, id from users where read_status = 1 '
		db.query(sql0, (err, result) => {
			// res.send(result)
			result.forEach((e)=>{
				var arr = JSON.parse(e.read_list) 
				if(arr != null){  
					if (!arr.includes(JSON.parse(req.body.newId))) {  // 判断 newId 是否已经在数组中
						arr.push(JSON.parse(req.body.newId))  
						arr = JSON.stringify(arr) 
						const sql1 = 'update users set read_list = ? where id = ?'
						db.query(sql1, [arr, e.id], (err, result) => {
							if (err) return res.cc(err)
						})
					}  // if includes	
				}
			})
			res.send({
				status: 0,
				msg: '已发送全体成员'
			}) 
		})
	})
}

// 删除 deleteId 全体成员
exports.deleteAllDepartment = (req, res) => {
	const { deleteId } = req.body
	const sql = 'select read_list,read_status,id from users'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		result.forEach((e) => {
			if (e.read_status === 1) {
				let arr = JSON.parse(e.read_list)
				if(arr != null){
					arr = arr.filter(item => {
						return item != deleteId
					})
					arr = JSON.stringify(arr)
					const sql1 = 'update users set read_list = ? where id = ?'
					db.query(sql1, [arr, e.id], (err, result) => {
						if (err) return res.cc(err)
					})
				}
			}
		}) // forEach	
		res.send({
			status: 0,
			message: '全体成员通知删除成功'
		})	
	})
}

// 获取部门消息 参数 id department （如果是全体成员）
exports.getDepartmentMsg = (req, res) => {
	const { id, department } = req.body
	// 根据发布消息时候的部门获取到用户的部门消息 并形成 数组 
	const sql = 'select * from message where message_receipt_object = ? and message_status = 0 '
	db.query(sql, department, (err, results) => {
		if (err) return res.cc(err)
		let msgArr = []
		results.forEach((e) => {
			msgArr.push(e.id)  // id是消息id
		})
		// 更新用户的 未读列表 read_list 以及 read_status
		const sql1 = 'update users set read_list = ?, read_status = 1 where id = ?'
		db.query(sql1, [JSON.stringify(msgArr), id], (err, result) => {
			if (err) return res.cc(err)
			res.send({
				status: 0,
				id: id,
				read_list: msgArr
			})
		})
	})
}

// 获取部门消息
exports.getDepartmentMsgList = (req, res) => {
	const { department } = req.body
	const sql = 'select * from message where message_receipt_object = ? and message_status = 0 '
	db.query(sql, department, (err, results) => {
		if (err) return res.cc(err)
		res.send(results)
	})
}

// 返回用户的阅读列表及状态
exports.getReadListAndStatus = (req, res) => {
	const sql = 'select read_list, read_status from users where id = ?'
	db.query(sql, req.body.id, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 用户点击消息后, 对read_list内的数据进行删减 参数 消息的readId 以及 用户的id
exports.clickDelete = (req, res) => {
	const sql = 'select read_list from users where id = ?'
	db.query(sql, req.body.id, (err, result) => {
		if (err) return res.cc(err)
		// 第一步 需要把我们获取到的read_list 变成 JSON对象 
		// 第二步 对这个read_list进行一个过滤
		// 第三步 使用JSON.stringify 变回原样 同时，update 这个用户的 read_list
		var lis = JSON.parse(result[0].read_list).filter(item => item != req.body.readId)  // 从 read_list 中移除指定的项目 ID
		var list = JSON.stringify(lis) 
		const sql1 = 'update users set read_list = ? where id = ?'
		db.query(sql1, [list, req.body.id], (err, result) => {
			if (err) return res.cc(err)
			res.send({
				status: 0,
				message: '删减成功'
			})
		})
	})
}

// 把新发布文章的id插入到当前所属部门的用户的read_list中 参数 新发布文章的newid 对应的部门 department
exports.changeUserReadList = (req, res) => {
	const { newId, department } = req.body
  // 只能往数组里面添加，不能往null添加（insert）,所以先筛选
	const sql0 = 'select read_list,read_status,id from users where department = ?'
	db.query(sql0, department, (err, result) => {
		if (err) return res.cc(err)
		var arr = []
		// [ RowDataPacket { read_list: '[11]', read_status: 1, id: 42 }, RowDataPacket { read_list: '[10]', read_status: 1, id: 43 }]
		result.forEach((e) => {
			if (e.read_status === 1) {  // 说明获得了read_list	 
				arr = JSON.parse(e.read_list) 
				if(arr != null){
					if (!arr.includes(JSON.parse(newId))) {  // 判断 newId 是否已经在数组中
						arr.push(JSON.parse(newId))  
						arr = JSON.stringify(arr)
						const sql = 'update users set read_list = ? where id = ?'
						db.query(sql, [arr, e.id], (err, result) => {
							if (err) return res.cc(err)
						})
					}  // if includes	
				}
			}
		})   // forEach	
		//  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 通常表示您在一个请求的响应中多次尝试设置响应头或发送响应
		res.send({
			status: 0,
			message: '更新成功',
			arrReadList: arr
		})			
	})
}

// 把删除的文章的id从当前所属部门的用户的read_list中删除 参数 新发布文章的deleteId 对应的部门 department
exports.changeUserReadListButDelete = (req, res) => {
	const { deleteId, department } = req.body
	const sql = 'select read_list,read_status,id from users where department = ?'
	db.query(sql, department, (err, result) => {
		if (err) return res.cc(err)
		result.forEach((e) => {
			if (e.read_status === 1) {
				let arr = JSON.parse(e.read_list)
				if(arr != null){
					arr = arr.filter(item => {
						return item != deleteId
					})
					arr = JSON.stringify(arr)
					const sql1 = 'update users set read_list = ? where id = ?'
					db.query(sql1, [arr, e.id], (err, result) => {
						if (err) return res.cc(err)
					})
				}
			}
		}) // forEach	
		res.send({
			status: 0,
			message: '删除成功'
		})	
	})
}

// id deleteId department
exports.changeUserReadListButDeleteById = (req, res) => {
	const { deleteId, department, id } = req.body
	const sql = 'select read_list,read_status,id from users where department = ?'
	db.query(sql, department, (err, result) => {
		if (err) return res.cc(err)
		result.forEach((e) => {
			if (e.read_status === 1) {
				let arr = JSON.parse(e.read_list)
				arr = arr.filter(item => {
					return item != deleteId
				})
				arr = JSON.stringify(arr)
				const sql1 = 'update users set read_list = ? where id = ?'
				db.query(sql1, [arr, id], (err, result) => {
					if (err) return res.cc(err)
				})
			}
		}) // forEach	
		res.send({
			status: 0,
			message: '删除成功'
		})	
	})
}